from django.http import JsonResponse, QueryDict
from django.views import View
from kubernetes import client, config
from libs import k8s
import os,json

class clusterrole_api(View):

    k8s.load_auth_config()
    rbac_api = client.RbacAuthorizationV1Api()

    def get(self,request):
        # 查询
        search_key = request.GET.get('query')

        data = []  # [{},{},{}]
        try:
            for item in self.rbac_api.list_cluster_role().items:
                name = item.metadata.name
                create_time = k8s.timestamp_format(item.metadata.creation_timestamp)
                d = {"name": name, "create_time": create_time}
                if search_key:
                    if search_key in name:  # 实现模糊匹配
                        data.append(d)
                else:
                    data.append(d)
            code = 200
            msg = "查询成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:  #  400 格式错误，409 资源存在，403 没权限。
                msg = "没有访问权限！"
            else:
                msg = "查询失败！"
            code = 500

        count = len(data)
        # 分页
        page = int(request.GET.get('pageNum', 1))  # 当前第几页
        limit = int(request.GET.get('pageSize',10))   # 当前页的数据数量
        start = (page - 1) * limit  # 获取切片的起始值
        end = page * limit # 获取切片的结束值
        data = data[start:end]

        result = {'code': code, 'msg': msg, 'count': count, 'data': data}
        return JsonResponse(result)
    def post(self,request):
        pass
    def delete(self,request):
        # 删除
        data = json.loads(request.body.decode("utf-8"))
        name = data['name']
        try:
            self.rbac_api.delete_cluster_role(name=name)
            code = 200
            msg = "删除成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "没有访问权限！"
            else:
                msg = "删除失败！"
            code = 500
        result = {'code': code, 'msg': msg}
        return JsonResponse(result)
    def put(self,request):
        pass


class clusterrolebinding_api(View):

    k8s.load_auth_config()
    rbac_api = client.RbacAuthorizationV1Api()

    def get(self,request):
        # 查询
        search_key = request.GET.get('query')

        data = []  # [{},{},{}]
        try:
            for item in self.rbac_api.list_cluster_role_binding().items:
                name = item.metadata.name
                namespace = item.metadata.namespace
                role_ref = item.role_ref.name
                subjects = item.subjects if item.subjects is not None else []
                subjects = [{"kind": s.kind, "name": s.name, "namespace": s.namespace} for s in subjects]
                create_time = k8s.timestamp_format(item.metadata.creation_timestamp)

                d = {"name": name, "namespace": namespace, "role_ref": role_ref, "subjects": subjects, "create_time": create_time}
                if search_key:
                    if search_key in name:  # 实现模糊匹配
                        data.append(d)
                else:
                    data.append(d)
            code = 200
            msg = "查询成功"

        except Exception as e:
            status = getattr(e, "status")
            if status == 403:  #  400 格式错误，409 资源存在，403 没权限。
                msg = "没有访问权限！"
            else:
                msg = "查询失败！"
            code = 500

        count = len(data)
        # 分页
        page = int(request.GET.get('pageNum', 1))  # 当前第几页
        limit = int(request.GET.get('pageSize',10))   # 当前页的数据数量
        start = (page - 1) * limit  # 获取切片的起始值
        end = page * limit # 获取切片的结束值
        data = data[start:end]

        result = {'code': code, 'msg': msg, 'count': count, 'data': data}
        return JsonResponse(result)
    def post(self,request):
        pass
    def delete(self,request):
        # 删除
        data = json.loads(request.body.decode("utf-8"))
        name = data['name']
        try:
            self.rbac_api.delete_cluster_role_binding(name=name)
            code = 200
            msg = "删除成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "没有访问权限！"
            else:
                msg = "删除失败！"
            code = 500
        result = {'code': code, 'msg': msg}
        return JsonResponse(result)
    def put(self,request):
        # 更新
        pass


class role_api(View):

    k8s.load_auth_config()
    rbac_api = client.RbacAuthorizationV1Api()

    def get(self,request):
        # 查询
        search_key = request.GET.get('query')
        namespace = request.GET.get('namespace')

        data = []  # [{},{},{}]
        try:
            for item in self.rbac_api.list_namespaced_role(namespace).items:
                name = item.metadata.name
                namespace = item.metadata.namespace
                create_time = k8s.timestamp_format(item.metadata.creation_timestamp)
                d = {"name": name, "namespace": namespace, "create_time": create_time}
                if search_key:
                    if search_key in name:  # 实现模糊匹配
                        data.append(d)
                else:
                    data.append(d)
            code = 200
            msg = "查询成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:  #  400 格式错误，409 资源存在，403 没权限。
                msg = "没有访问权限！"
            else:
                msg = "查询失败！"
            code = 500

        count = len(data)
        # 分页
        page = int(request.GET.get('pageNum', 1))  # 当前第几页
        limit = int(request.GET.get('pageSize',10))   # 当前页的数据数量
        start = (page - 1) * limit  # 获取切片的起始值
        end = page * limit # 获取切片的结束值
        data = data[start:end]

        result = {'code': code, 'msg': msg, 'count': count, 'data': data}
        return JsonResponse(result)
    def post(self,request):
        pass

    def delete(self, request):
        # 删除
        data = json.loads(request.body.decode("utf-8"))
        name = data['name']
        namespace = data.get('namespace')
        try:
            self.rbac_api.delete_namespaced_role(namespace=namespace, name=name)
            code = 200
            msg = "删除成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "没有访问权限！"
            else:
                msg = "删除失败！"
            code = 500
        result = {'code': code, 'msg': msg}
        return JsonResponse(result)

    def put(self, request):
        # 更新
        pass


class rolebinding_api(View):

    k8s.load_auth_config()
    rbac_api = client.RbacAuthorizationV1Api()

    def get(self,request):
        # 查询
        search_key = request.GET.get('query')
        namespace = request.GET.get('namespace')

        data = []  # [{},{},{}]
        try:
            for item in self.rbac_api.list_namespaced_role_binding(namespace).items:
                name = item.metadata.name
                namespace = item.metadata.namespace
                role_ref = "%s (%s)" %(item.role_ref.name, item.role_ref.kind)
                subjects = item.subjects if item.subjects is not None else []
                subjects = [{"kind": s.kind, "name": s.name, "namespace": s.namespace} for s in subjects]
                create_time = k8s.timestamp_format(item.metadata.creation_timestamp)
                d = {"name": name, "namespace": namespace, "role_ref": role_ref, "subjects": subjects, "create_time": create_time}
                if search_key:
                    if search_key in name:  # 实现模糊匹配
                        data.append(d)
                else:
                    data.append(d)
            code = 200
            msg = "查询成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:  #  400 格式错误，409 资源存在，403 没权限。
                msg = "没有访问权限！"
            else:
                msg = "查询失败！"
            code = 500

        count = len(data)
        # 分页
        page = int(request.GET.get('pageNum', 1))  # 当前第几页
        limit = int(request.GET.get('pageSize',10))   # 当前页的数据数量
        start = (page - 1) * limit  # 获取切片的起始值
        end = page * limit # 获取切片的结束值
        data = data[start:end]

        result = {'code': code, 'msg': msg, 'count': count, 'data': data}
        return JsonResponse(result)
    def post(self,request):
        pass
    def delete(self,request):
        # 删除
        data = json.loads(request.body.decode("utf-8"))
        name = data['name']
        namespace = data.get('namespace')
        try:
            self.rbac_api.delete_namespaced_role(namespace=namespace, name=name)
            code = 200
            msg = "删除成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "没有访问权限！"
            else:
                msg = "删除失败！"
            code = 500
        result = {'code': code, 'msg': msg}
        return JsonResponse(result)
    def put(self,request):
        # 更新
        pass